const { Material, Category, Tag } = require('../models')
const { Op } = require('sequelize')
const path = require('path')
const fs = require('fs').promises
const { processWatermark } = require('../utils/watermark')

// 获取资料列表
exports.getMaterials = async (req, res) => {
  try {
    const { categoryId, search, page = 1, limit = 10 } = req.query
    const offset = (page - 1) * limit

    const where = {}
    if (categoryId) where.categoryId = categoryId
    if (search) where.title = { [Op.like]: `%${search}%` }

    const materials = await Material.findAll({
      where,
      limit: parseInt(limit),
      offset: parseInt(offset),
      include: [
        {
          model: Category,
          as: 'category',
          attributes: ['id', 'name']
        },
        {
          model: Tag,
          as: 'tags',
          attributes: ['id', 'name', 'color'],
          through: { attributes: [] }
        }
      ]
    })

    res.json({
      success: true,
      data: materials
    })
  } catch (error) {
    console.error('获取资料列表错误:', error)
    res.status(500).json({
      success: false,
      message: '获取资料列表失败'
    })
  }
}

// 获取资料详情
exports.getMaterialById = async (req, res) => {
  try {
    const material = await Material.findByPk(req.params.id, {
      include: [
        {
          model: Category,
          as: 'category',
          attributes: ['id', 'name']
        },
        {
          model: Tag,
          as: 'tags',
          attributes: ['id', 'name', 'color'],
          through: { attributes: [] }
        }
      ]
    })

    if (!material) {
      return res.status(404).json({
        success: false,
        message: '资料不存在'
      })
    }

    res.json({
      success: true,
      data: material
    })
  } catch (error) {
    console.error('获取资料详情错误:', error)
    res.status(500).json({
      success: false,
      message: '获取资料详情失败'
    })
  }
}

// 更新资料
exports.updateMaterial = async (req, res) => {
  try {
    const material = await Material.findByPk(req.params.id)
    if (!material) {
      return res.status(404).json({
        success: false,
        message: '资料不存在'
      })
    }

    // 验证权限
    if (req.user.role !== 'admin' && material.uploaderId !== req.user.id) {
      return res.status(403).json({
        success: false,
        message: '无权修改此资料'
      })
    }

    const { title, description, categoryId, price, noWatermarkPrice, tags } = req.body

    // 更新资料信息
    await material.update({
      title,
      description,
      categoryId,
      price,
      noWatermarkPrice
    })

    // 更新标签
    if (tags && Array.isArray(tags)) {
      const tagInstances = await Tag.findOrCreateTags(tags)
      await material.setTags(tagInstances)
    }

    res.json({
      success: true,
      message: '资料更新成功',
      data: await Material.findByPk(material.id, {
        include: [
          {
            model: Category,
            as: 'category',
            attributes: ['id', 'name']
          },
          {
            model: Tag,
            as: 'tags',
            attributes: ['id', 'name', 'color'],
            through: { attributes: [] }
          }
        ]
      })
    })
  } catch (error) {
    console.error('更新资料错误:', error)
    res.status(500).json({
      success: false,
      message: '更新资料失败'
    })
  }
}

// 删除资料
exports.deleteMaterial = async (req, res) => {
  try {
    const material = await Material.findByPk(req.params.id)
    if (!material) {
      return res.status(404).json({
        success: false,
        message: '资料不存在'
      })
    }

    // 验证权限
    if (req.user.role !== 'admin' && material.uploaderId !== req.user.id) {
      return res.status(403).json({
        success: false,
        message: '无权删除此资料'
      })
    }

    // 删除文件
    await fs.unlink(material.filePath).catch(() => {})
    await fs.unlink(material.noWatermarkFilePath).catch(() => {})
    await fs.unlink(material.thumbnailPath).catch(() => {})

    // 删除数据库记录
    await material.destroy()

    res.json({
      success: true,
      message: '资料删除成功'
    })
  } catch (error) {
    console.error('删除资料错误:', error)
    res.status(500).json({
      success: false,
      message: '删除资料失败'
    })
  }
}

// 上传资料
exports.uploadMaterial = async (req, res) => {
  try {
    const { 
      title, 
      description, 
      categoryId, 
      price, 
      noWatermarkPrice,
      tags,
      watermarkText,
      watermarkPosition,
      watermarkOpacity
    } = req.body

    // 验证必填字段
    if (!title || !categoryId || !req.file) {
      return res.status(400).json({
        success: false,
        message: '请提供所有必填字段'
      })
    }

    // 验证分类是否存在
    const category = await Category.findByPk(categoryId)
    if (!category) {
      return res.status(400).json({
        success: false,
        message: '所选分类不存在'
      })
    }

    // 处理水印
    const watermarkOptions = {
      text: watermarkText || '标王资料网',
      opacity: parseFloat(watermarkOpacity) || 0.5,
      position: watermarkPosition || 'bottom-right'
    }

    // 原始文件路径
    const originalPath = req.file.path
    // 带水印文件路径
    const watermarkedPath = path.join(
      path.dirname(originalPath),
      `watermarked_${path.basename(originalPath)}`
    )

    // 生成带水印版本
    await processWatermark(originalPath, watermarkedPath, watermarkOptions)

    // 生成缩略图
    const { generateThumbnail } = require('../utils/thumbnailGenerator')
    const thumbnailPath = path.join(
      path.dirname(originalPath),
      `thumbnail_${path.basename(originalPath)}.png`
    )
    await generateThumbnail(originalPath, thumbnailPath)

    // 创建资料记录
    const material = await Material.create({
      title,
      description,
      categoryId,
      price: parseInt(price) || 0,
      noWatermarkPrice: parseInt(noWatermarkPrice) || 0,
      filePath: watermarkedPath, // 带水印版本
      noWatermarkFilePath: originalPath, // 原始版本
      thumbnailPath, // 缩略图路径
      fileSize: req.file.size,
      fileType: path.extname(req.file.originalname).toLowerCase(),
      uploaderId: req.user.id,
      watermarkText: watermarkOptions.text,
      watermarkPosition: watermarkOptions.position,
      watermarkOpacity: watermarkOptions.opacity,
      isApproved: req.user.role === 'admin' // 管理员上传的资料自动审核通过
    })

    // 处理标签
    if (tags && Array.isArray(tags)) {
      const tagInstances = await Tag.findOrCreateTags(tags)
      await material.setTags(tagInstances)
    }

    res.status(201).json({
      success: true,
      message: '资料上传成功',
      data: {
        material: await Material.findByPk(material.id, {
          include: [
            {
              model: Category,
              as: 'category',
              attributes: ['id', 'name']
            },
            {
              model: Tag,
              as: 'tags',
              attributes: ['id', 'name', 'color'],
              through: { attributes: [] }
            }
          ]
        })
      }
    })
  } catch (error) {
    console.error('上传资料错误:', error)
    res.status(500).json({
      success: false,
      message: '服务器错误'
    })
  }
}

// 保留原有的下载相关方法
exports.generateDownloadLink = async (req, res) => {
  // ... 原有代码 ...
}

exports.downloadFile = async (req, res) => {
  // ... 原有代码 ...
}

function generateTempToken() {
  // ... 原有代码 ...
}